<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';

// 接收从父组件传递过来的数据列表
const props = defineProps({
  dataList: Array
});

const chartContainer = ref(null);
let myChart = null;

const updateChart = (rawData) => {
  if (!myChart) return;
    // --- 数据清洗和过滤 ---
  const filteredData = rawData.filter(item => {
    // 1. 检查日期是否有效
    const isValidDate = item.udt && !isNaN(new Date(item.udt));
    if (!isValidDate) return false;

    // 2. 检查数值是否是合理的数字，并排除异常值 65536
    const yl1 = parseFloat(item.j1);
    const yl2 = parseFloat(item.j2);
    const isReasonableYl1 = !isNaN(yl1) && yl1 < 20; // 假设液流通道一不会超过1
    const isReasonableYl2 = !isNaN(yl2) && yl2 < 20; // 假设液流通道二不会超过1

    return isReasonableYl1 && isReasonableYl2;
  });

  myChart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['液流通道一', '液流通道二'] },
    xAxis: {
      type: 'category',
      data: filteredData.map(item => new Date(item.udt).toLocaleString()),
      axisLabel: {
        color: '#ccc'
      }
    },
    yAxis: { type: 'value',
      axisLabel: {
        color: '#ccc'
      }
    },
    series: [
      {
        name: '液流通道一',
        type: 'line',
        smooth: true,
        data: filteredData.map(item => item.j1)
      },
      {
        name: '液流通道二',
        type: 'line',
        smooth: true,
        data: filteredData.map(item => item.j2)
      }
    ]
  });
};

onMounted(() => {
  myChart = echarts.init(chartContainer.value,'dark');
  updateChart(props.dataList);
});

// 监听数据变化，并更新图表
watch(() => props.dataList, (newData) => {
  updateChart(newData);
}, { deep: true });
</script>

<template>
  <div class="chart-wrapper">
    <h2>实时数据曲线</h2>
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<style scoped>
.chart-wrapper {
  margin-top: 2rem;
  padding: 1rem;
  border: 1px solid #eee;
  border-radius: 8px;
}
</style>

